<template>
  <div class="layout-header">
    <div class="header-left" @click="goHome">
      <img v-if="config.basic && config.basic.system_square_logo" :src="config.basic.system_square_logo" alt=""
        class="header-logo" />
      <span class="title-txt" v-if="config.basic && config.basic.system_name">{{
        configData.site_name || config.basic.system_name
      }}</span>
      <span class="header-left-tip">{{
        configData.site_subtitle || "AI智能助理"
      }}</span>
    </div>
    <div class="menu-list align-center flex" v-if="menuList.length > 0">
      <a-menu mode="horizontal" :selectedKeys="selectedMenu" @click="handleMenuClick" style="width: 520px">
        <a-menu-item v-for="item in menuList" :key="item.name">
          <!-- <cu-icon :type="item.meta.icon" style="font-size: 16px"></cu-icon> -->
          {{ item.meta.title }}
        </a-menu-item>
      </a-menu>
      <div class="search-box ml-20">
        <a-input placeholder="请输入要搜索的内容" style="width: 180px; cursor: pointer; border-radius: 10px" readonly
          @click="onClickSearchInput">
          <template #prefix>
            <SearchOutlined />
          </template>
        </a-input>
      </div>
    </div>
    <div class="header-right">
      <a-row style="padding-right: 10px">
        <div class="icon-function" @click="toVip">
          <cu-icon class="icon card-icon" type="icon-Member"></cu-icon>
          <div>会员</div>
          <span class="dot"></span>
        </div>
        <div class="icon-function icon-function-bg" @click="showWechatAccount" v-if="wechatAccountExist">
          <cu-icon class="icon card-icon" type="icon-shouji"></cu-icon>
          <div>公众号</div>
        </div>
        <div class="icon-function" @click="toHelper" v-if="aiConfig.help_url">
          <cu-icon class="icon card-icon" type="icon-iconfontzhizuobiaozhunbduan21"></cu-icon>
          <div>帮助</div>
        </div>
        <a-popover trigger="hover">
          <template #content>
            <div style="
                width: 120px;
                display: flex;
                justify-content: center;
                flex-direction: column;
                align-items: center;
                color: #999999;
              ">
              <div style="width: 115px; height: 115px; margin-bottom: 5px">
                <img style="width: 100%; height: 100%" :src="service_qrcode" />
              </div>
              <div>微信扫码咨询客服</div>
            </div>
          </template>
          <div class="icon-function">
            <cu-icon class="icon card-icon" type="icon-kefu"></cu-icon>
            <div>客服</div>
          </div>
        </a-popover>
      </a-row>

      <template v-if="isLogin">
        <a-dropdown v-if="userInfo && userInfo.id">
          <div class="user-wrap">
            <div class="user">
              <img v-if="userInfo.avatar" :src="userInfo.avatar" alt="" class="user-avatar" />
              <a-avatar v-else class="user-outlined">
                <template #icon>
                  <UserOutlined />
                </template>
              </a-avatar>
              <span class="user-nickname" v-if="userInfo.nickname">{{
                userInfo.nickname
              }}</span>
              <span class="user-nickname" v-else>微信用户</span>
            </div>
          </div>
          <template #overlay>
            <a-menu>
              <a-menu-item>
                <a-button type="text" @click="toUserSetting">
                  <template #icon>
                    <UserOutlined />
                  </template>
                  账号设置
                </a-button>
              </a-menu-item>
              <a-menu-item>
                <a-button type="text" @click="toOrderList">
                  <template #icon>
                    <UnorderedListOutlined />
                  </template>
                  订单管理
                </a-button>
              </a-menu-item>
              <a-menu-item>
                <a-button type="text" @click="toAccountCenter">
                  <template #icon>
                    <UserOutlined />
                  </template>
                  账号中心
                </a-button>
              </a-menu-item>
              <a-menu-item>
                <a-button type="text" @click="toCreateCenter">
                  <template #icon>
                    <UserOutlined />
                  </template>
                  创作中心
                </a-button>
              </a-menu-item>
              <a-menu-item>
                <a-button type="text" @click="logout">
                  <template #icon>
                    <LoginOutlined />
                  </template>
                  退出登录
                </a-button>
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </template>
      <template v-else>
        <a-button type="primary" @click="loginVisible = true">注册/登录</a-button>
      </template>
    </div>

    <wechatAccountModal :visible="wechatAccountVisible" @getResult="wechatAccountGetResult"
      @onClose="wechatAccountVisible = false" />

    <LoginModal :visible="loginVisible" @onClose="loginVisible = false" @loginCallback="loginCallback" />
    <SearchModal v-model:visible="searchModalVisible" />

    <BindPhone :visible="bindPhoneVisible" @onClose="onCloseBindPhone" @loginCallback="bindPhoneCallback" />
  </div>
</template>

<script>
import {
  defineComponent,
  reactive,
  ref,
  toRefs,
  computed,
  watch,
  toRaw,
  h,
  onBeforeUnmount,
  createVNode,
  inject,
} from "vue";
import request from "../../common/utils/request";
import store from "../../store/index";
import { useRoute, useRouter } from "vue-router";
import utils from "../../common/utils/utils";
import { Modal, notification, message } from "ant-design-vue";
import {
  PlusOutlined,
  ExclamationCircleOutlined,
  CloseCircleFilled,
  LoginOutlined,
  UnorderedListOutlined,
  UserOutlined,
  SearchOutlined,
} from "@ant-design/icons-vue";
import QRCode from "qrcode";
import wechatAccountModal from "../../components/WechatAccountModal/index.vue";
import routes from "../../router/router.config";
import routerConfig from "../../router/router.config";
import SearchModal from "../../components/SearchModal/index.vue";
import BindPhone from "../../components/BindPhone/index.vue";

export default defineComponent({
  name: "LayoutHeader",
  components: {
    LoginOutlined,
    UnorderedListOutlined,
    UserOutlined,
    SearchOutlined,
    wechatAccountModal,
    SearchModal,
    BindPhone,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },

  setup(props, context) {
    const route = useRoute();
    const router = useRouter();

    const state = reactive({
      loginVisible: false,
      userInfo: {},
      config: {},
      service_qrcode: "",
      wechatAccountVisible: false,
      configData: {},

      menuList: [],
      // 当前选中菜单
      selectedMenu: [],
      aiConfig: {},

      sceneApplicationList: [], //AI应用
      sceneIndustryList: [], //AI行业

      wechatAccountExist: false, //是否有微信公众号

      bindPhoneVisible: false,
    });

    const loginCallback = () => {
      state.loginVisible = false;
      router.go(0);
    };

    // 判断菜单是否显示
    const getMenuShow = (menu) => {
      return menu.meta && menu.meta.permission && !menu.meta.hidden;
    };

    const getShowMenuList = (menuList, result = []) => {
      for (let menu of menuList) {
        if (getMenuShow(menu)) {
          let menuItem = {
            path: menu.path,
            name: menu.name,
            component: menu.component,
            meta: menu.meta,
          };
          if (
            (menu.name !== "SceneModel" && menu.name !== "IndustryModel") ||
            (menu.name == "SceneModel" &&
              state.sceneApplicationList.length > 0) ||
            (menu.name == "IndustryModel" && state.sceneIndustryList.length > 0)
          ) {
            if (menu.name == "PaintModel") {
              if (state.aiConfig.ai_draw_open) {
                result.push(menuItem);
              }
            } else {
              result.push(menuItem);
            }
          }
        }
      }
    };

    // 切换菜单路由
    const handleMenuClick = ({ item, key, keyPath }) => {
      router.push({ name: key });
      state.selectedMenu = [key];
    };

    const getMatchRouteShow = (matchList) => {
      for (let item of matchList) {
        if (getMenuShow(item)) {
          return true;
        }
      }
      return false;
    };

    // 初始化当前路由
    const initMenuList = (init = false) => {
      if (init) {
        const menuRoutes = routes.find((item) => item.name == "workGPT");
        store.dispatch("getAiConfig").then((aiConfig) => {
          if (aiConfig) {
            state.aiConfig = aiConfig;
          }
          getShowMenuList(menuRoutes.children, state.menuList);
          //根据当前路由匹配到一级菜单
          let currentRoutePath = router.currentRoute.value.path;
          if (currentRoutePath) {
            let currentRoutePathArr = currentRoutePath.split("/");
            if (currentRoutePathArr.length >= 2) {
              let currentMenu = state.menuList.find(
                (item) => item.path == currentRoutePathArr[1]
              );
              if (currentMenu && currentMenu.name) {
                state.selectedMenu = [currentMenu.name];
              } else {
                state.selectedMenu = ["Home"];
              }
            }
          }
        });
      }
    };

    const init = () => {
      store.dispatch("GetSceneApps").then((sceneApps) => {
        if (sceneApps) {
          if (sceneApps.applicationList) {
            state.sceneApplicationList = sceneApps.applicationList;
          }

          if (sceneApps.industryList) {
            state.sceneIndustryList = sceneApps.industryList;
          }
          initMenuList(true);
        }
      });

      store.dispatch("GetConfigInfo").then((config) => {
        if (config && config.basic && config.basic.system_name) {
          state.config = config;
        }
      });

      utils.getUserInfo().then((userInfo) => {
        state.userInfo = userInfo;
        if (userInfo && !utils.validatePhoneNumber(userInfo?.phone)) {
          if (utils.getStorage("tipCache_work_ai_bindPhone")) {
            state.bindPhoneVisible = false;
          } else {
            state.bindPhoneVisible = true;
          }
        }
      });

      request.get("/work_ai", "/config").then(async (res) => {
        store.dispatch("SetAiConFig", JSON.stringify(res.list));
        state.configData = res.list;
        if (res.list && res.list.baidu_statistics_id) {
          // 加入百度统计代码
          var _hmt = _hmt || [];
          window._hmt = _hmt; // 将_hmt挂载到window下
          (function () {
            var hm = document.createElement("script");
            hm.src =
              "https://hm.baidu.com/hm.js?" + res.list.baidu_statistics_id;
            var s = document.getElementsByTagName("script")[0];
            s.parentNode.insertBefore(hm, s);
          })();
        }

        if (res.list && res.list.service_qrcode) {
          state.service_qrcode = res.list.service_qrcode;
        }
      });
    };

    const logout = () => {
      utils.modalConfirm({
        content: "确定退出登录吗？",
        centered: true,
        onOk: () => {
          store.dispatch("Logout").then(() => {
            context.emit("refresh");
            router.push({ name: "Home" });
            setTimeout(() => {
            }, 200);
          });
        },
      });
    };

    const toOrderList = () => {
      router.push({
        name: "Order",
      });
    };

    // 会员
    const toVip = () => {
      utils.checkLogin().then((isLogin) => {
        if (!isLogin) {
          state.loginVisible = true;
          return;
        }
        router.push({
          name: "Vip",
        });
      });
    };

    // 团队管理
    const toTeamSetting = () => {
      utils.checkLogin().then((isLogin) => {
        if (!isLogin) {
          state.loginVisible = true;
          return;
        }
        router.push({
          name: "TrainingAppList",
        });
      });
    };

    const goHome = () => {
      router.replace("/sceneModel/work");
    };

    const showWechatAccount = () => {
      state.wechatAccountVisible = true;
    };

    init();

    const isLogin = computed(() => {
      return store.getters.isLogin;
    });

    // 当二级路由发生变化时（点击左侧菜单)
    const onSecondRouteChange = (parentRoutePath) => {
      const menuRoutes = routerConfig.find((item) => item.name == "workGPT");

      if (menuRoutes && menuRoutes.children) {
        const currentMenuRoute = menuRoutes.children.find(
          (item) => item.path == parentRoutePath
        );
        state.selectedMenu = [currentMenuRoute.name];
      }
    };

    watch(route, () => {
      let flag = false;
      let lastRoutePath = router.options.history.state.back;
      if (lastRoutePath && lastRoutePath.indexOf("?") != -1) {
        lastRoutePath = lastRoutePath.split("?")[0];
      }
      let currentRoutePath = router.currentRoute.value.path;
      let lastRoutePathArr = [];
      let currentRoutePathArr = [];
      if (lastRoutePath && currentRoutePath) {
        lastRoutePathArr = lastRoutePath.split("/");
        currentRoutePathArr = currentRoutePath.split("/");
        if (
          lastRoutePathArr.length > 1 &&
          currentRoutePathArr.length > 1 &&
          lastRoutePathArr[1] == currentRoutePathArr[1]
        ) {
          flag = true;
        }
      }

      // 相同一级菜单下，二级菜单切换时
      if (flag) {
        onSecondRouteChange(currentRoutePathArr[1]);
      } else {
        if (route.meta.firstRouteAlias) {
          state.selectedMenu = [route.meta.firstRouteAlias];
        }
      }
    });

    // 账号设置
    const toUserSetting = () => {
      utils.checkLogin().then((isLogin) => {
        if (!isLogin) {
          state.loginVisible = true;
          return;
        }
        router.push({
          name: "UserSetting",
        });
      });
    };

    watch(
      () => store.getters.userInfo,
      (val) => {
        // 修改用户信息后，清空用户信息重新获取渲染
        if (!val) {
          utils.checkLogin().then((isLogin) => {
            if (!isLogin) {
              state.loginVisible = true;
              return;
            }
            utils.getUserInfo().then((userInfo) => {
              state.userInfo = userInfo;
            });
          });
        }
      }
    );

    const searchModalVisible = ref(false);

    const onClickSearchInput = () => {
      searchModalVisible.value = true;
    };

    const wechatAccountGetResult = (result) => {
      if (result) {
        state.wechatAccountExist = true;
      }
    };
    const toAccountCenter = () => {
      router.push({
        name: "AccountCenter",
      });
    };
    const toCreateCenter = () => {
      router.push({
        name: "CreateCenter",
      });
    };


    const bindPhoneCallback = () => {
      state.bindPhoneVisible = false;
      utils.setStorage("tipCache_work_ai_bindPhone", true, false);
    };

    const onCloseBindPhone = () => {
      state.bindPhoneVisible = false;
      utils.setStorage("tipCache_work_ai_bindPhone", true, false);
    };

    const toHelper = () => {
      window.open(state.aiConfig.help_url, '_blank');
    }

    return {
      ...toRefs(state),
      loginCallback,
      logout,
      toOrderList,
      toVip,
      toTeamSetting,
      goHome,
      showWechatAccount,
      isLogin,
      handleMenuClick,
      toUserSetting,
      onClickSearchInput,
      searchModalVisible,
      wechatAccountGetResult,
      toAccountCenter,
      toCreateCenter,
      bindPhoneCallback,
      onCloseBindPhone,
      toHelper
    };
  },
});
</script>

<style lang="less" scoped>
.layout-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  position: relative;

  .header-left {
    display: flex;
    align-items: center;
    cursor: pointer;

    .header-logo {
      width: 36px;
      height: 36px;
      object-fit: cover;
      border-radius: 8px;
    }

    .title-txt {
      margin-left: 10px;
      font-size: 18px;
      font-weight: 600;
    }

    .header-left-tip {
      color: #8c8c8c;
      margin-left: 15px;
      font-size: 12px;
    }
  }

  .menu-list {
    flex: 1;
    padding: 0 20px;

    :deep(.ant-menu) {
      border: none;

      .ant-menu-item {
        height: 44px;
        line-height: 44px;
        font-size: 16px;

        &::after {
          border: none !important;
        }
      }
    }
  }

  .header-right {
    height: 60px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .user-wrap {
      height: 100%;
      padding: 8px 0;

      .user {
        cursor: pointer;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 0 10px;
        border-radius: 4px;
        min-width: 134px;

        .user-avatar {
          width: 26px;
          height: 26px;
          border-radius: 50%;
        }

        .user-nickname {
          margin-left: 10px;
          color: #666;
        }

        &:hover {
          background-color: #f5f5f5;
        }
      }
    }

    .icon-function {
      text-align: center;
      line-height: 18px;
      color: #000000a6;
      font-size: 12px;
      cursor: pointer;
      border-radius: 5px;
      position: relative;
      width: 60px;
      height: 50px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      &:hover {
        background-color: #f5f5f5;
        color: @primary-color;
      }

      .icon {
        font-size: 19px;
      }

      .dot {
        position: absolute;
        width: 6px;
        height: 6px;
        background-color: #ff4d4f;
        border-radius: 50%;
        top: 6px;
        right: 6px;
      }
    }

    .user-outlined {
      background-color: @primary-color;
    }
  }
}

@media screen and (max-width: 1500px) {
  .layout-header {
    .search-box {
      display: none;
    }
  }
}
</style>
